﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using YunShop_WebAPI.BLL;

namespace YunShop_WebAPI.Model
{


    public enum WxSystemAppID
    {
        HostID = 0,
        CorpID = 1,
        StockID = 2,
        WeixinID = 3,
        MemberID = 4,
        HostIPStr = 5,
        DbSplitID = 6,
    }

    public class WxSystemInfo
    {
        private static string AESKey = "k&WX@)!%09!AC8WB";
        public static string GetClusterHostIP(string mSystemAppID, int mCorpID)
        {
            string sDbHostIP = "";
            try
            {
                mSystemAppID = mSystemAppID.Replace(' ', '+');
                string sDecAppID = Decrypt(mSystemAppID);
                sDbHostIP = ConvertToString(sDecAppID.Split(',')[(int)WxSystemAppID.HostIPStr]);
            }
            catch
            {
            }
            if (string.IsNullOrEmpty(sDbHostIP))
            {
                sDbHostIP = GetClusterHostIP(mCorpID);
            }
            return sDbHostIP;
        }

        public static string GetClusterHostIP(int mCorpID)
        {
            string sql = string.Format(@"SELECT FDbHostIP FROM t_CorpHost where FMinCorpID <= {0} and FMaxCorpID >= {0}", mCorpID);

            ArrayList dataAll = DBHelper.Select(sql, DBHelper.ConnMaster);
            if (dataAll.Count > 0)
            {
                Hashtable record = (Hashtable)dataAll[0];
                return CommonFun.ConvertToString(record["FDbHostIP"]);
            }
            else
            {
                return "";
            }
        }

        public static int getSystemAppID(string dSystemAppJson, SystemAppID idType)
        {
            try
            {
                dSystemAppJson = dSystemAppJson.Replace(' ', '+');
                string sDecAppID = Decrypt(dSystemAppJson);
                int sSystemAppID = ConvertToInt(sDecAppID.Split(',')[(int)idType]);
                return sSystemAppID;
            }
            catch
            {
                return 0;
            }
        }

        public static int GetSplitCorpID(int mCorpID)
        {
            string msql = string.Format(@"SELECT FParentID FROM dbo.t_Corpration with(NOLOCK) where FItemID = {0} and FParentID > 0", mCorpID);
            ArrayList dataCorp = DBHelper.Select(msql, DBHelper.ConnMaster);
            if (dataCorp.Count > 0)
            {
                Hashtable record0 = (Hashtable)dataCorp[0];//如果有上级，分库标识和上级相同
                return ConvertToInt(record0["FParentID"]);
            }
            return mCorpID;
        }

        public static string GetClusterSplit(int mCorpID)
        {
            string sql = string.Format(@"SELECT FDbSplit FROM t_CorpHost where FMinCorpID <= {0} and FMaxCorpID >= {0}", GetSplitCorpID(mCorpID));
            ArrayList dataAll = DBHelper.Select(sql, DBHelper.ConnMaster);
            if (dataAll.Count > 0)
            {
                Hashtable record = (Hashtable)dataAll[0];
                return ConvertToString(record["FDbSplit"]);
            }
            return ".";
        }

        public static string GetClusterConn(int mCorpID)
        {
            string sql = string.Format(@"SELECT FDbHostIP FROM t_CorpHost where FMinCorpID <= {0} and FMaxCorpID >= {0}", mCorpID);

            ArrayList dataAll = DBHelper.Select(sql, DBHelper.ConnMaster);
            if (dataAll.Count > 0)
            {
                Hashtable record = (Hashtable)dataAll[0];
                return ConvertToString(record["FDbHostIP"]);
            }
            else
            {
                return "";
            }
        }

        public static int GetSystemAppID(string dSystemAppJson, WxSystemAppID idType)
        {
            try
            {
                dSystemAppJson = dSystemAppJson.Replace(' ', '+');
                string sDecAppID = Decrypt(dSystemAppJson);
                int sSystemAppID =   ConvertToInt(sDecAppID.Split(',')[(int)idType]);
                return sSystemAppID;
            }
            catch
            {
                return 0;
            }
        }

        public static string SetSystemAppID(int HostId, int mCorpId, Int64 mStockID, Int64 mWeixinID, Int64 mMemberID, string sHostIP)
        {
            try
            {
                //服务器ID+商户ID+仓库ID+微信ID+会员ID+数据服务器IP
                string mSystemID = ConvertToInt(HostId) + "," + mCorpId.ToString() + "," + mStockID.ToString()
                    + "," + mWeixinID.ToString() + "," + mMemberID.ToString() + "," + sHostIP;//系统用户的身份
                string sSystemAppID = Encrypt(mSystemID);
                return sSystemAppID;
            }
            catch
            {
                return "";
            }
        }

        public static string ConvertToString(Object obj)
        {
            try
            {
                if (obj == null)
                {
                    return "";
                }
                if (obj == DBNull.Value)
                {
                    return "";
                }
                return Convert.ToString(obj);
            }
            catch (Exception E)
            {
                return "";
            }
        }

        public static int ConvertToInt(object obj)
        {
            try
            {
                if (obj == null)
                {
                    return 0;
                }
                if (obj == DBNull.Value)
                {
                    return 0;
                }
                return Convert.ToInt32(obj);
            }
            catch (Exception E)
            {
                return 0;
            }
        }

        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="decryptStr">密文</param>
        /// <param name="key">密钥</param>
        /// <returns></returns>
        public static string Decrypt(string decryptStr)
        {
            try
            {
                string key = AESKey;
                byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
                byte[] toEncryptArray = Convert.FromBase64String(decryptStr);
                RijndaelManaged rDel = new RijndaelManaged();
                rDel.Key = keyArray;
                rDel.Mode = CipherMode.ECB;
                rDel.Padding = PaddingMode.PKCS7;
                ICryptoTransform cTransform = rDel.CreateDecryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
                return UTF8Encoding.UTF8.GetString(resultArray);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        
        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="encryptStr">明文</param>
        /// <param name="key">密钥</param>
        /// <returns></returns>
        public static string Encrypt(string encryptStr)
        {
            string key = AESKey;
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(encryptStr);
            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = rDel.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }



    }

}
